// cloudfunctions/getMyPosts/index.js
const cloud = require('wx-server-sdk');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    const { userId, page = 1, pageSize = 10 } = event;
    
    // 验证参数
    if (!userId) {
      return { success: false, message: '缺少userId参数' };
    }
    
    // 计算分页参数
    const skip = (page - 1) * pageSize;
    
    // 查询我的帖子
    const postsResult = await db.collection('community_posts')
      .where({
        userId: userId
      })
      .orderBy('createTime', 'desc')
      .skip(skip)
      .limit(pageSize)
      .get();
    
    // 查询总数量
    const totalResult = await db.collection('community_posts')
      .where({
        userId: userId
      })
      .count();
    
    return {
      success: true,
      data: {
        list: postsResult.data,
        total: totalResult.total
      },
      message: '获取我的帖子成功'
    };
  } catch (error) {
    console.error('获取我的帖子失败', error);
    return {
      success: false,
      message: error.message || '服务器错误',
      error: error.message
    };
  }
};